//
//  LoginViewController.swift
//  YunCang
//
//  Created by wangshuning on 16/7/27.
//  Copyright © 2016年 hddden. All rights reserved.
//



import UIKit

import MMDrawerController
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class LoginViewController: UIViewController,UITextFieldDelegate  {
    
    @IBOutlet weak var passwordClear: UIButton!
    @IBOutlet weak var userClear: UIButton!
    @IBOutlet weak var logoWith: NSLayoutConstraint!
    @IBOutlet weak var logoImage: UIImageView!
    @IBOutlet weak var topSpace: NSLayoutConstraint!
    
    @IBOutlet weak var centerCon: NSLayoutConstraint!
    @IBOutlet weak var btnCon: NSLayoutConstraint!
    @IBOutlet weak var bgCon: NSLayoutConstraint!
    
//    @IBOutlet weak var desLabel: UILabel!
    @IBOutlet weak var setButton: UIButton!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var userName: UITextField!
    @IBOutlet weak var lineLabel: UILabel!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var imageView: UIImageView!
    
    //#MARK: – Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        //读取用户信息
        self.userName.text = userInfo!.userName
        // Do any additional setup after loading the view.
        
        //遵守UITextFieldDelegate
        topSpace.constant = KscreenHeight / 667 * 113
        userName.delegate = self
        password.delegate = self
        userName.returnKeyType = UIReturnKeyType.next
        password.returnKeyType = UIReturnKeyType.go
        password.isSecureTextEntry = true
        userClear.isHidden = true
        passwordClear.isHidden = true
        passwordClear.isSelected = false
        passwordClear!.setBackgroundImage(UIImage(named: "Cancel-hover"), for: UIControlState.highlighted)
        userClear!.setBackgroundImage(UIImage(named: "Cancel-hover"), for: UIControlState.highlighted)
        userName.tintColor = UIColor.hexStringToUIColor("#00acff")
        password.tintColor = UIColor.hexStringToUIColor("#00acff")
        //设置Button的状态和颜色
        loginButton.setTitleColor(UIColor.white, for: UIControlState.disabled)
        loginButton.setBackgroundImage(UIImage(named: "矩形-2-拷贝"), for: UIControlState.disabled)
        loginButton.isEnabled = false
        
        //给View添加手势
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.hideKeyboard))
        self.view.addGestureRecognizer(gestureRecognizer)
        
        //给键盘添加通知
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.change), name: NSNotification.Name.UITextFieldTextDidChange, object: self.userName)
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.change), name: NSNotification.Name.UITextFieldTextDidChange, object: self.password)
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.userClearchange), name: NSNotification.Name.UITextFieldTextDidChange, object: self.userName)
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.passwordClearchange), name: NSNotification.Name.UITextFieldTextDidChange, object: self.password)
    
        
    }
   
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: "\(LoginViewController.self)", bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        password.resignFirstResponder()
        userName.resignFirstResponder()
        self.navigationController?.navigationBar.isHidden = true
        self.quitlogin()
    }

    //设置状态栏颜色
    override var preferredStatusBarStyle : UIStatusBarStyle {
        return UIStatusBarStyle.default
    }

    //#MARK:通知方法 – Private Method
    func userClearchange() {
        if (userName.text?.characters.count > 0) {
            userClear.isHidden = false
            
        }else{
            userClear.isHidden = true
        }
    }
    
    
    func passwordClearchange() {
        if (password.text?.characters.count>0) {
            passwordClear.isHidden = false
        }else{
            passwordClear.isHidden = true
        }
    }
    
    func change() {
        if (userName.text?.characters.count > 0 && password.text?.characters.count>0) {
            loginButton.isEnabled = true
            loginButton.setBackgroundImage(UIImage(named: "矩形-2"), for: UIControlState())
            loginButton.setTitleColor(UIColor.white, for: UIControlState())
            
        }else{
            loginButton.isEnabled = false
            loginButton.setBackgroundImage(UIImage(named: "矩形-2-拷贝"), for: UIControlState.disabled)
        }
    }
    //键盘隐藏
    func hideKeyboard() {
        userName.resignFirstResponder()
        password.resignFirstResponder()
    }

    //键盘显示的时候，按钮向上跑，不会被遮盖
    func keyboardShow(_ textField: UITextField) {
        //获取键盘的高度
//        let userInfo = noti.userInfo as!AnyObject
//        let heightValue = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)as!NSValue
//        let keyboardRect = heightValue.CGRectValue()
//        print(keyboardRect.height)
//        print(loginButton.y)
        
        self.topSpace.constant = KscreenHeight / 667 * 113 - 50
        self.bgCon.constant = 10*KscreenHeight/320
        self.btnCon.constant = 10*KscreenHeight/320
        self.logoWith.constant = 90*KscreenWidth/320
        
        UIView.animate(withDuration: 0.25, animations: {
            self.view.layoutIfNeeded()
        }, completion: { (finished) in
            
        }) 
    }
    //收回键盘的方法
    func keyboardHide() {
        self.topSpace.constant = KscreenHeight / 667 * 113
        self.bgCon.constant = 51
        self.btnCon.constant = 40
        self.logoWith.constant = 118
        print(loginButton)
        UIView.animate(withDuration: 0.25, animations: {
         self.view.layoutIfNeeded()
        }, completion: { (finished) in

        }) 
    }

    //#MARK: – UITextFieldDelegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool{
        if textField == userName {
             password.becomeFirstResponder()
        }
        if textField == password {
           self.login()
        }
        return true
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == userName && userName.text?.characters.count > 0 {
            userClear.isHidden = false
        }
        if textField == password && password.text?.characters.count > 0{
            passwordClear.isHidden = false
        }
        
        return true
    }
    func textFieldDidEndEditing(_ textField: UITextField) {

        if textField == userName {
            userClear.isHidden = true
        }
        if textField == password {
            passwordClear.isHidden = true
        }
    }

    //#MARK: – IBAtions
    @IBAction func passwordClear(_ sender: AnyObject) {
        self.password.text = ""
        passwordClear.isHidden = true
        loginButton.isEnabled = false
        loginButton.setBackgroundImage(UIImage(named: "矩形-2-拷贝"), for: UIControlState.disabled)
    }

    @IBAction func userClear(_ sender: AnyObject) {
        self.userName.text = ""
        userClear.isHidden = true
        loginButton.isEnabled = false
        loginButton.setBackgroundImage(UIImage(named: "矩形-2-拷贝"), for: UIControlState.disabled)
    }
    @IBAction func setButton(_ sender: AnyObject) {
         let  setCVC = ServerViewController()
         self.present(setCVC, animated: true, completion: nil)
    }
    
    func quitlogin()  {
        
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: "userName")
        defaults.removeObject(forKey: "userPassword")
        defaults.set(false, forKey:"Login")
        defaults.synchronize()
        
    }
    
    func retainlogin() {
        let userDefaults = UserDefaults.standard
        userDefaults.set(userName.text, forKey: "userName")
        userDefaults.set(password.text, forKey: "userPassword")
        userDefaults.set(true, forKey: "Login")
        userDefaults.synchronize()
    }

    
    @IBAction func loginButton(_ sender: AnyObject) {
        self.login()
    }

    func login() {
        if ConfigGlobal.getRootIP().rootIP == nil && ConfigGlobal.getRootIP().IPName == nil {
            let alert = UIAlertView.init(title: "IP为空或错误", message: "请设置IP", delegate: self, cancelButtonTitle:" 确定")
            alert.show()
        } else {
            
            passwordClear.isHidden = true
            NetworkTool.sharedTools.postSoap(["Password":EncryptionTool.encryptString(password.text!),"Username":userName.text!], bodyParam: ["piPassWord":password.text!,"piUserName":userName.text!], bodyMethod: "chkUser", success: { responseXml in
                
                if (analysisManager.shareManager.XmlParserAnalysis(responseXml, elementName:"chkUserResponse").first!["chkUserResult"]! == "0") {
                    userInfo?.userName = self.userName.text ?? ""
                    userInfo?.userPassWord = self.password.text ?? ""//登陆成功，储存最新的用户信息
                    self.loginButton.setTitleColor(UIColor.green, for: UIControlState())
                    let app = UIApplication.shared
                    let app2 = app.delegate
                    let  yunCVC = YunCangViewController()
                    let  centerNVC = YunCenterViewController(rootViewController: yunCVC)
                    let leftVC = YunLeftTableViewController()
                    let  drawerController = MMDrawerController.init(center: centerNVC, leftDrawerViewController: leftVC)
                    app2?.window!!.rootViewController = drawerController
                    drawerController?.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.all
                    drawerController?.maximumLeftDrawerWidth = 270
                    self.navigationController?.present(drawerController!, animated: true, completion: nil)
                    self.password.resignFirstResponder()
                    self.userName.resignFirstResponder()
                    self.retainlogin()
                }else {
                    let alert = UIAlertView.init(title: "用户名或密码错误", message: "请重新登录", delegate: self, cancelButtonTitle:" 确定")
                    alert.show()
                }
                
            }) {
                let alert = UIAlertView.init(title: "没有网络或IP设置有误", message: "请检查网络或重新设置IP", delegate: self, cancelButtonTitle:" 确定")
                alert.show()
            }
            
        }

        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
